package DAO;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import Beans.ComandaBean;
import Beans.ItemVentaBean;
import Beans.VentaBean;
import Controller.AdministradorVenta;
import HibernateUtils.HibernateUtil;
import Model.Venta;

public class HibernateVentaDAO {

	
	private static HibernateVentaDAO instancia = null;
	private static SessionFactory sf = null;

	public static HibernateVentaDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new HibernateVentaDAO();
		} 
		return instancia;
	}
	
	public void grabarVenta(VentaBean vb){
		//VentaBean vb=AdministradorVenta.getInstancia().fromModelTOBean(v);
		
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(vb);;
		session.flush();
		session.getTransaction().commit();
		session.close();
		
		
	}

	public VentaBean getVenta(int nroMesa) {
		Session session = sf.openSession();
		Query q=session.createQuery("from VentaBean v where v.nroMesa=? ").setInteger(0, nroMesa);
		q.setFirstResult(0).setMaxResults(1);
		Object o=q.uniqueResult();
		VentaBean venta=(VentaBean)o;
		return venta;
		
		
		
	}

	public void updateVenta(VentaBean vb) {
		Session session = sf.openSession();
		session.beginTransaction();
		session.update(vb);;
		session.flush();
		session.getTransaction().commit();
		session.close();
		
	}

	public ComandaBean buscarComanda(VentaBean v) {
		Session session =sf.openSession();
		Query q=session.createQuery("select c from VentaBean v join v.comandas"
				+ " c where v.idVenta=? and c.estado=?").setInteger(0, v.getIdVenta()).setString(1, "no despachada");
		
		ComandaBean cb=(ComandaBean)q.uniqueResult();
		//session.flush();
		//sf.close();
		return cb;
	}

	public VentaBean buscarVenta(VentaBean ab) {
		Session session=sf.openSession();
		VentaBean venta=(VentaBean) session.get(VentaBean.class,ab.getIdVenta());
		session.close();
		return venta;
	}

	public ItemVentaBean buscarItemVenta(ItemVentaBean ab) {
		Session session=sf.openSession();
		ItemVentaBean item=(ItemVentaBean) session.get(ItemVentaBean.class,ab.getIdItemVenta());
		session.close();
		return item;
	}

	
}
